var fruits = generageReviewMap();
if (fruits.size == 0) {
    tip("暂时没有单词需要复习o_o");
}
var keyIsDown = false;
var round = 0;
/*
 *  wrongCounts [round=>[3,2,4,1,0,...] , round=>[], ...  ]
 */
var wrongCounts = new Array();
var nowWord = "";
var nowWordIndex = 0;
var wrongCount = 0;
    wrongCounts[round] = new Array();
const cardContainer = document.getElementById('input-container');
var keys = fruits.keys();
var values = fruits.values();
w = keys.next().value;
nowWord = values.next().value[0];
updateInputer();
up(w);

function updateInputer() {
    var index = 0;
    cardContainer.innerHTML = "";
    while (index < nowWord.length) {
        card = document.createElement('input');
        card.className = 'input-field slide-left';
        card.setAttribute('maxlength', 1);
        card.setAttribute('oninput', `handleInput(${index},event)`);
        card.setAttribute('onkeyup', `handleKeyUp(${index},this, event)`);
        card.setAttribute('onkeydown', `handleKeyDown(${index},this, event)`);
        cardContainer.appendChild(card);
        index++;
    }
    document.querySelector('.input-field').focus();
}

function setTip(ii) {
    inputs = document.querySelectorAll('.input-field');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].value = ""
    }
    //alert(nowWord);
    arr = nowWord.split('');
    for (var i = 0; i <= ii; i++) {
        inputs[i].setAttribute("placeholder" ,arr[i]);
    }
    inputs[0].focus();
}

function up(str) {
    document.querySelector('.word-shower').innerHTML = str;
}

function tip(str) {
    document.querySelector('.tip-shower').innerHTML = str;
}

function inputOver() {
    inputs = document.querySelectorAll('.input-field');
    return inputs[inputs.length - 1].value != "";
}

function getInput(inputs) {
    str = "";
    for (i = 0; i < inputs.length; i++) {
        str = str + inputs[i].value;
    }
    return str;
}

$("#restart-test").click(function() {
    keys = fruits.keys();
    values = fruits.values();
    w = keys.next().value;
    nowWord = values.next().value[0];
    round++;
    nowWordIndex = 0;
    wrongCounts[round] = new Array();
    updateInputer();
    up(w);
    document.querySelector('.tip-shower').setAttribute("style", "font-size: 95px;line-height: 110px;")
    tip("");
    $("#restart-test").css("display","none");

});

function handleInput(currentIndex, event) {
    const inputs = document.querySelectorAll('.input-field');
    // console.log(currentIndex + inputs[currentIndex].value);
    if (currentIndex <= inputs.length - 1 && inputs[currentIndex].value !== "") {
        if (keyIsDown) {
            if(inputs[currentIndex].value == "?" || inputs[currentIndex].value == "？") {
                if(wrongCount < nowWord.length) {
                    inputs[currentIndex].value = "";
                    tip("浅浅给你提示一下");
                    e = document.querySelector('.word-shower');
                    e.classList.add('horizon-shake');
                    setTimeout(() => {
                        e.classList.remove('slide-right');
                        e.classList.remove('horizon-shake');
                    }, 500);
                    setTip(wrongCount);
                    wrongCount++;
                }
            } else {
                if (currentIndex < inputs.length - 1) {
                    inputs[currentIndex + 1].focus();
                }
            }
            keyIsDown = false;
        } else {
            inputs[currentIndex].value = "";
            return;
        }
    }

    if (currentIndex == inputs.length - 1 && inputs[inputs.length - 1].value != "") {
        //console.log("  "+currentIndex+inputs[currentIndex].value);
        inp = getInput(inputs);
        setTimeout(function () {
            document.getElementById("main").scrollIntoView();
        }, 250);
        if (nowWord == inp || document.getElementById("Upper-Checkbox").checked && nowWord.toLowerCase() == inp.toLowerCase()) {
            wrongCounts[round][nowWordIndex++] = wrongCount;
            wrongCount = 0;
            tip("答对了，你真棒");
            w = keys.next().value;
            nowWord = values.next().value;
            if (nowWord == undefined) {
                document.querySelector('.word-shower').innerHTML = ">_<"
                document.querySelector('.tip-shower').setAttribute("style", "font-size: 30px;line-height: 35px;")
                let str = "";
                let i = 1;
                let testPassed = true;
                for (let [key, value] of fruits) {
                    str = str + `第${i}个单词：${key}(${value[0]})  错误次数：${wrongCounts[round][i - 1]}<br />`;
                    if (wrongCounts[round][i - 1] > 1) {
                        testPassed = false;
                    }
                    i++;
                }
                if(testPassed) {
                    let i = 0;
                    let averageWrongCounts = new Map();
                    for (let k of fruits.keys()) {
                        averageWrongCounts.set(k,0);
                    }
                    while(i <= round && i < 2) {
                        keys = fruits.keys();
                        for (let j = 0; j < wrongCounts[i].length; j++) {
                            let k = keys.next().value;
                            let w = averageWrongCounts.get(k);
                            w += wrongCounts[i][j];
                           //console.log(w,wrongCounts[i][j]);
                            averageWrongCounts.set(k,w);
                        }
                        i++
                    }
                    for (let k of fruits.keys()) {
                        let w = averageWrongCounts.get(k);
                        w /= i;
                        let wT = Math.trunc(w);
                        w = (w-wT > 0) ? (wT + 1) : (wT);
                        averageWrongCounts.set(k,w);
                    }
                    for (let entry of averageWrongCounts) {
                        //console.log(entry[1]);
                        let content = fruits.get(entry[0]);
                        content[2] = entry[1];
                        fruits.set(entry[0],content);
                    }
                    let result = updateReviewedWords(fruits);
                    if (result == "0") {
                        str += "<br />恭喜你完成了本次复习！ 你的复习已被记录到云端";
                    } else {
                        str += "<br />上传数据到服务器时出现了未知错误"+result;
                    }
                } else {
                    str += "<br />测试尚未通过 x_x  点击下方按钮开始重复测试，当每个单词均错误少于2次时测试通过";
                    $("#restart-test").css("display","inline-block")
                }
                tip("第" + round + "轮结束，以下是作答情况：<br />" + str + "<br />提示次数也会视为错误次数");
            } else {
                nowWord = nowWord[0];
                updateInputer();
                up(w);
            }  //下次复习时间点(天) 1   2.37   6   15    57     95      240
               //单词熟练度       1200 3000 7500 18900 47683  120300  303500
        } else {
            e = document.querySelector('.word-shower');
            e.classList.add('horizon-shake');
            setTimeout(() => {
                e.classList.remove('slide-right');
                e.classList.remove('horizon-shake');
            }, 500);

            if (wrongCount >= nowWord.length) {
                tip("给你机会你不中用啊<br />现在自己删了重打");
            } else {
                setTip(wrongCount);
                wrongCount++;
                tip("答错了，你真笨<br />再给你一次机会");
            }
        }
    }
}

var lastback = -1;

function handleKeyDown(i, input, event) {
    keyIsDown = true;
    //console.log(3);
    if (event.keyCode === 8 && input.previousElementSibling) {
        if (input.value != "") {
            lastback = i;
        }
    } else if (input.nextElementSibling) {
        if (input.value != "") {
            //console.log(2);
            input.nextElementSibling.focus();
        }
    }
}

function handleKeyUp(i, input, event) {
    //console.log(4);
    if (event.keyCode === 8 && input.previousElementSibling) {
        if (lastback != i) {
            input.previousElementSibling.value = "";
        }
        lastback = -1;
        input.previousElementSibling.focus();
    }
}
